package com.otitan.la.forest.industry.client.http.methods;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @Description: java类作用描述
 * @Author: jiachangsen
 * @CreateDate: 2020/10/15 11:36
 * @UpdateUser: jiachangsen
 * @UpdateDate: 2020/10/15 11:36
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Data
@Slf4j
public abstract class AbstractHttpClient implements HttpClient {
    public AbstractHttpClient(){};
    public AbstractHttpClient(String path, String token, Object params) {
        this.path = path;
        this.token = token;
        this.params = params;
    }

    HttpRequestBase httpClient;

    public static final String CONTENT_TYPE_FORM_DATA = "application/x-www-form-urlencoded";

    public static final String  CONTENT_TYPE_JSON = "application/json";

    String path;

    public String token;

    public Object params;

    public String dataStr;

    public byte[] dataByte;

    public Integer statusCode;

    public HttpEntity httpEntity;

    private HttpPost post;

    /**
     * 发送 post 请求
     * @author jiachangsen
     * @param [mediaType, entity]
     * @return java.lang.String
     * @exception
     * @date 2020/10/15 12:42
     */
    public String postRequest(String mediaType, HttpEntity entity) {
        post = new HttpPost(path);
        post.addHeader("Content-Type", mediaType);
        post.addHeader("Accept", "application/json");
        if (StrUtil.isNotEmpty(token)){
            post.addHeader(Header.AUTHORIZATION.getValue(), token);
        }
        post.setEntity(entity);
        try {
            //设置超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(CONNECT_TIMEOUT)
                    .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
                    .setSocketTimeout(CONNECT_TIMEOUT).build();
            post.setConfig(requestConfig);

            org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
            HttpResponse response = client.execute(post);
            statusCode = response.getStatusLine().getStatusCode();
            httpEntity = response.getEntity();
            if (statusCode >= 400) {
                log.error("【请求错误】 状态码：{}, ", statusCode);
            }
        } catch (ClientProtocolException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return null;
    }

    @Override
    public void releaseConnection() {
        if (post != null){
            post.releaseConnection();
        }
    }

    public String readStr(){
        if (statusCode == 200){
            try {
                return EntityUtils.toString(httpEntity, StandardCharsets.UTF_8);
            } catch (IOException e) {
                log.error("读取返回结果失败！错误信息：{}",e.getMessage());
            }
        }
        return null;
    }

    public byte[] readByte(){
        if (statusCode == 200){
            try {
                return EntityUtils.toByteArray(httpEntity);
            } catch (IOException e) {
                log.error("读取返回结果失败！错误信息：{}",e.getMessage());
            }
        }
        return null;
    }
}
